package com.woniuxy.service.impl;

import com.woniuxy.service.UserGoodsService;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserGoodsServiceImpl implements UserGoodsService {
    private static final String USER_SEARCH_HISTORY_PREFIX = "USER:SEARCH:HISTORY:";
    private static final int MAX_HISTORY_SIZE = 10; // 最多保存10条记录
    private static final long HISTORY_TTL_DAYS = 30;

    @Resource
    private RedisTemplate<String, String> redisTemplateInit;

    public List<String> findHistorySearchByUser(Integer userId) {
        // 使用List结构存储
        String key = USER_SEARCH_HISTORY_PREFIX + userId;
        Long size = redisTemplateInit.opsForList().size(key);

        if (size == null || size == 0) {
            return Collections.emptyList();
        }

        // 获取最近N条记录
        return redisTemplateInit.opsForList()
                .range(key, 0, Math.min(size, MAX_HISTORY_SIZE) - 1);
    }

    public void saveHistorySearchByUser(String goodsKey, Integer userId) {
        if (StringUtils.isBlank(goodsKey)) {
            return;
        }

        String key = USER_SEARCH_HISTORY_PREFIX + userId;

        // 1. 移除已存在的相同记录（去重）
        redisTemplateInit.opsForList().remove(key, 0, goodsKey);

        // 2. 添加到列表头部
        redisTemplateInit.opsForList().leftPush(key, goodsKey);

        // 3. 修剪列表，只保留最近MAX_HISTORY_SIZE条
        redisTemplateInit.opsForList().trim(key, 0, MAX_HISTORY_SIZE - 1);

        // 4. 设置过期时间
        redisTemplateInit.expire(key, HISTORY_TTL_DAYS, TimeUnit.DAYS);
    }
}
